package com.lian.chatroom.server.handler;

import com.lian.chatroom.message.ChatRequestMessage;
import com.lian.chatroom.message.ChatResponseMessage;
import com.lian.chatroom.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 聊天请求处理器
 * SimpleChannelInboundHandler可以用泛型指定消息类型
 * 这样只有遇到 ChatRequestMessage 类消息，才会触发此handler处理器
 */
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        //获取收信人
        String to = msg.getTo();
        //根据收信人获取与其绑定的通道
        Channel channel = SessionFactory.getSession().getChannel(to);
        //如果用户在线
        if (channel != null){
            //将聊天响应信息刷新到通道中，将发送人和发送消息写到收信人的通道里
            channel.writeAndFlush(new ChatResponseMessage(msg.getFrom(),msg.getContent()));
        }else {
            //如果用户不在线
            ctx.writeAndFlush(new ChatResponseMessage(false,"对方用户不存在或者不在线"));
        }

    }
}
